import { Mark,mergeAttributes,Node } from '@tiptap/core'
import Paragraph from '@tiptap/extension-paragraph'
import { VueNodeViewRenderer } from '@tiptap/vue-3'
import { Plugin, PluginKey } from 'prosemirror-state';
import SceneHeader from './SceneHeader.vue'
import dayjs from 'dayjs'

// 场头节点配置
export const SceneHeaderNode = Node.create({
    name: 'sceneHeader',
    group: 'block',
    atom: false,  // ❌ 原来是 atom: true，去掉！
    content:'',
    defining: true,
    isolating: true,
    selectable: true,
    draggable: false,
    addAttributes() {
      return {
        id: { default: '' },
        episode: { default: '' },
        scene: { default: '' },
        sceneName: { default: '' },
        mood: { default: '' },
        interiorExteriorScene: { default: '' },
        editing: { default: true },
        isNew:{ default:true }
      }
    },
  
    parseHTML() {
      return [{
        tag: 'div[data-scene-header]',
        getAttrs: el => ({
          id: el.getAttribute('id') || '',
          episode: el.getAttribute('data-episode') || '',
          scene: el.getAttribute('data-scene') || '',
          sceneName: el.getAttribute('data-scene-name') || '',
          mood: el.getAttribute('data-mood') || '室内',
          interiorExteriorScene: el.getAttribute('data-interior-exterior-scene') || '白天',
          editing: el.getAttribute('data-editing') === 'true',
          isNew: el.getAttribute('data-isNew') === 'true',
        }),
      }]
    },
  
    renderHTML({ HTMLAttributes }) {
      return ['div', {
        'id':HTMLAttributes.id,
        'data-scene-header': 'true',
        'data-episode': HTMLAttributes.episode,
        'data-scene': HTMLAttributes.scene,
        'data-scene-name': HTMLAttributes.sceneName,
        'data-mood': HTMLAttributes.mood,
        'data-interior-exterior-scene': HTMLAttributes.interiorExteriorScene,
        'data-editing': HTMLAttributes.editing,
        'data-isNew': HTMLAttributes.isNew,
        'style': 'height: 70px'
      }]
    },
  
    addNodeView() {
      return VueNodeViewRenderer(SceneHeader)
    },
  
    // 在 SceneHeaderNode 中更新 insertSceneHeaderWithFocus 命令逻辑
    addCommands() {
      return {
        insertSceneHeaderWithFocus:
          () =>
          ({ state, dispatch }) => {
            const { schema, tr, selection } = state
            const { from } = selection
    
            // 创建场头节点
            const sceneHeaderNode = schema.nodes.sceneHeader.create({
              id: dayjs().valueOf().toString(),
              editing: true,
              episode: '',
              scene: '',
              sceneName: '',
              mood: '',
              interiorExteriorScene: '',
            })
    
            // 替换当前选区为场头节点
            tr.replaceSelectionWith(sceneHeaderNode)
    
            // 再插入一个段落节点紧跟其后
            const sceneHeaderPos = tr.mapping.map(from)
            const paragraph = schema.nodes.paragraph.create()
    
            // 确保段落插在 sceneHeader 后面
            const insertPos = tr.mapping.map(sceneHeaderPos + sceneHeaderNode.nodeSize)
            tr.insert(insertPos, paragraph)
    
            // 设置光标到这个新段落的开头
            const TextSelection = state.selection.constructor
            const resolved = tr.doc.resolve(insertPos + 1)
            tr.setSelection(TextSelection.near(resolved))
    
            // dispatch 更新
            if (dispatch) {
              dispatch(tr)
            }
    
            return true
          },
        deleteSceneHeaderBlock:
          (pos) =>
          ({ state, dispatch }) => {
            const { doc, tr } = state
            let endPos = doc.content.size
  
            // 查找下一个 sceneHeader 的位置（跨页）
            doc.descendants((node, posHere) => {
              if (posHere > pos && node.type.name === 'sceneHeader') {
                endPos = posHere
                return false // stop descending
              }
              return true
            })
  
            tr.delete(pos, endPos)
  
            if (dispatch) {
              dispatch(tr)
            }
  
            return true
          }
      }
    }
    
  })

// 文字类型
export const TextTypeMark = Mark.create({
    name: 'textType',
    addAttributes() {
      return {
        text_type: {
          default: null,
          parseHTML: element => element.getAttribute('text_type'),
          renderHTML: attributes => {
            return attributes.text_type
              ? { text_type: attributes.text_type }
              : {}
          },
        },
        data_style: {
          default: null,
          parseHTML: element => element.getAttribute('data_style') || null,
          renderHTML: attributes => {
            return attributes.data_style
              ? { style: attributes.data_style }
              : {}
          },
        },
      }
    },
  
    parseHTML() {
      return [
        {
          tag: 'span[text_type]',
        },
      ]
    },
  
    renderHTML({ HTMLAttributes }) {
      return ['span', mergeAttributes(HTMLAttributes), 0]
    },
    toDOM(mark) {
        return [
          'span',
          {
            text_type: mark.attrs.text_type,
            style: styles[mark.attrs.text_type]
              ? Object.entries(styles[mark.attrs.text_type])
                  .map(([k, v]) => `${k}: ${v};`)
                  .join(' ')
              : '',
          },
          0
        ]
      }
  })

// CustomParagraph.js
// 段落
export const CustomParagraph = Paragraph.extend({
  addAttributes() {
    return {
      class: {
        default: null,
      },
    }
  },
})
  
  
  